package org.sgmiller.quickstem.tests;

import org.sgmiller.quickstem.IsolationLevel;
import org.sgmiller.quickstem.Transaction;
import org.sgmiller.quickstem.collections.TransactionalMultiArray;

public class Benchmark {

	public static void main(String[] args) {
		final int array[][] = { { 5, 6, 7 }, { 4, 8, 9 } };
		final int array1[][] = { { 6, 4 }, { 5, 7 }, { 1, 1 } };
		final int x = array.length;
		System.out.println("Matrix 1 : ");
		for (int i = 0; i < x; i++) {
			for (int j = 0; j <= x; j++) {
				System.out.print(" " + array[i][j]);
			}
			System.out.println();
		}
		final int y = array1.length;
		System.out.println("Matrix 2 : ");
		for (int i = 0; i < y; i++) {
			for (int j = 0; j < y - 1; j++) {
				System.out.print(" " + array1[i][j]);
			}
			System.out.println();
		}
		long start = 0;

		int[][] matrix = null;
		for (int l = 0; l < 5; l++) {
			matrix = new int[3][3];
			start = System.currentTimeMillis();
			for (int b = 0; b < 100000; b++) {
				matrix = new int[3][3];
				for (int i = 0; i < x; i++) {
					for (int j = 0; j < y - 1; j++) {
						for (int k = 0; k < y; k++) {
							matrix[i][j] += array[i][k] * array1[k][j];
						}
					}
				}
			}
			System.out.println("Took " + (System.currentTimeMillis() - start)
					+ "ms");
		}
		System.out.println("Multiply of both matrix : ");
		for (int i = 0; i < x; i++) {
			for (int j = 0; j < y - 1; j++) {
				System.out.print(" " + matrix[i][j]);
			}
			System.out.println();
		}

		final TransactionalMultiArray<Integer> matrix2 = new TransactionalMultiArray<Integer>(
				0, new int[] { 3, 3 });
		// int[][] matrix = new int[3][3];
		Thread[] threads = new Thread[10];

		for (int l = 0; l < 100; l++) {
			start = System.currentTimeMillis();
			for (int i = 0; i < threads.length; i++) {
				threads[i] = new Thread(new Runnable() {

					@Override
					public void run() {
						Transaction.begin(IsolationLevel.READ_COMMITTED);
						for (int b = 0; b < 100000; b++) {

							// matrix = new int[3][3];
							for (int i = 0; i < x; i++) {
								for (int j = 0; j < y - 1; j++) {
									for (int k = 0; k < y; k++) {
										// matrix[i][j] += array[i][k] *
										// array1[k][j];
										matrix2.set(matrix2.get(i, j)
												+ array[i][k] * array1[k][j],
												i, j);
									}
								}
							}
						}
						/*
						 * System.out.println("Multiply of both matrix : "); for
						 * (int i = 0; i < x; i++) { for (int j = 0; j < y - 1;
						 * j++) { System.out.print(" "+matrix2.get(i,j));
						 * //System.out.print(" " + matrix[i][j]); }
						 * System.out.println(); }
						 */

						Transaction.rollback();
					}

				});
				threads[i].start();
			}
			for (int q = 0; q < threads.length; q++) {
				try {
					threads[q].join();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			System.out.println("Took " + (System.currentTimeMillis() - start)
					+ "ms");

		}
	}
}
